﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Web;

namespace AFT.Parking.Foundation.Utilities
{
    public class ImgHelper
    {
        /// <summary>
        /// 会产生graphics异常的PixelFormat
        /// </summary>
        private static PixelFormat[] indexedPixelFormats =
        {
            PixelFormat.Undefined, PixelFormat.DontCare,
            PixelFormat.Format16bppArgb1555, PixelFormat.Format1bppIndexed, PixelFormat.Format4bppIndexed,
            PixelFormat.Format8bppIndexed
        };
        /// <summary>
        /// 判断图片的PixelFormat 是否在 引发异常的 PixelFormat 之中
        /// </summary>
        /// <param name="imgPixelFormat">原图片的PixelFormat</param>
        /// <returns></returns>
        private static bool IsPixelFormatIndexed(PixelFormat imgPixelFormat)
        {
            foreach (PixelFormat pf in indexedPixelFormats)
            {
                if (pf.Equals(imgPixelFormat)) return true;
            }

            return false;
        }


        /// <summary>
        /// 画虚线或带箭头
        /// </summary>
        /// <param name="oldFile"></param>
        /// <param name="newFile"></param>
        /// <param name="startPoint"></param>
        /// <param name="endPoint"></param>
        public static void DrawDashOrArrow(string oldFile, string newFile, Point startPoint, Point endPoint, bool IsDash)
        {

            Bitmap image;
            Graphics g;
            using (Image img = Image.FromFile(oldFile))
            {
                if (IsPixelFormatIndexed(img.PixelFormat))
                {
                    image = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb);
                    g = Graphics.FromImage(image);
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.DrawImage(img, 0, 0);
                }
                else
                {
                    image = new Bitmap(oldFile);
                    g = Graphics.FromImage(image);
                }
                try
                {
                    Pen p = new Pen(Color.Red, 3);
                    p.DashPattern = new float[] {3, 2}; // 画虚线
                    if (IsDash) //画箭头
                    {
                        System.Drawing.Drawing2D.AdjustableArrowCap lineArrow =
                            new System.Drawing.Drawing2D.AdjustableArrowCap(4, 4, true);
                        p.CustomEndCap = lineArrow;
                    }
                    g.DrawLine(p, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
                    image.Save(newFile, ImageFormat.Jpeg);
                }
                finally
                {
                    g.Dispose();
                    image.Dispose();
                }
            }
        }

        /// <summary>
        /// 线路图
        /// </summary>
        /// <param name="img"></param>
        public static void DrawLine(ImgProccess img)
        {

            Bitmap image;
            Graphics g;
            using (Image i = Image.FromFile(img.OldFile))
            {
                if (IsPixelFormatIndexed(i.PixelFormat))
                {
                    image = new Bitmap(i.Width, i.Height, PixelFormat.Format32bppArgb);
                    g = Graphics.FromImage(image);
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.DrawImage(i, 0, 0);
                }
                else
                {
                    image = new Bitmap(img.OldFile);
                    g = Graphics.FromImage(image);
                }
                try
                {
                    Pen p = new Pen(Color.Red, 3);
                    if (img.IsDash) // 画虚线
                        p.DashPattern = new float[] { 3, 2 };
                    if (img.IsCap)//画箭头
                    {
                        System.Drawing.Drawing2D.AdjustableArrowCap lineArrow =
                            new System.Drawing.Drawing2D.AdjustableArrowCap(4, 4, true);
                        p.CustomEndCap = lineArrow;
                    }
                    foreach (var item in img.LinePoints) //画线段
                    {
                        g.DrawLine(p, item.StartPoint.X, item.StartPoint.Y, item.EndPoint.X, item.EndPoint.Y);
                    }

                    #region 画起点水印图

                    System.Drawing.Image startWaterImg = System.Drawing.Image.FromFile(img.StartWaterImg);
                    System.Drawing.Imaging.ImageAttributes _ImageAttributes = new System.Drawing.Imaging.ImageAttributes();

                    ColorMap colorMap = new ColorMap();
                    colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                    colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                    ColorMap[] remapTable = { colorMap };
                    _ImageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                    //第四行第四个值用来设置透明度，值越大越不透明: 1为不透明、0为全透明
                    //正对角线的值分别代表红、绿、蓝、透明度、第五个值也没做太深入研究，想了解ColorMatrix即5x5矩阵可以在网上搜一下，这个矩阵的各个值的设置听说还申请了专利。
                    float[][] colorMatrixElements = {  
                new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},  
                new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},  
                new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},  
                new float[] {0.0f, 0.0f, 0.0f, 0.9f, 0.0f},
                new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}  
                };
                    System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements);
                    _ImageAttributes.SetColorMatrix(colorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap);
                    g.DrawImage(startWaterImg, new System.Drawing.Rectangle(img.LinePoints[0].StartPoint.X - 25, img.LinePoints[0].StartPoint.Y - 50, startWaterImg.Width, startWaterImg.Height), 0, 0, startWaterImg.Width, startWaterImg.Height, System.Drawing.GraphicsUnit.Pixel, _ImageAttributes);
                    startWaterImg.Dispose();
                    #endregion

                    #region 画终点水印图
                    System.Drawing.Image endWaterImg = System.Drawing.Image.FromFile(img.EndWaterImg);
                    g.DrawImage(endWaterImg, new System.Drawing.Rectangle(img.LinePoints.Last().EndPoint.X - 25, img.LinePoints.Last().EndPoint.Y - 50, endWaterImg.Width, endWaterImg.Height), 0, 0, endWaterImg.Width, endWaterImg.Height, System.Drawing.GraphicsUnit.Pixel, _ImageAttributes);
                    endWaterImg.Dispose();
                    _ImageAttributes.Dispose();
                    #endregion

                    image.Save(img.NewFile, ImageFormat.Jpeg);
                }
                finally
                {
                    g.Dispose();
                    image.Dispose();
                }
            }
          
        }

        /// <summary>
        /// 生成缩略图，此方法省略两个参数：｛是否指定大小生成图片=按图片比例缩放，是否需要打上水印=不打水印｝
        /// </summary>
        /// <param name="inputstream">Image文件流</param>
        /// <param name="newFile">生成的文件名称；注：全路径</param>
        /// <param name="maxWidth">生成图片的宽</param>
        /// <param name="maxHeight">生成图片高</param>
        /// <param name="Quality">生成图片质量</param>
        public static void MakeThumbnail(Stream inputstream, string newFile, int maxWidth, int maxHeight, int Quality)
        {
            System.Drawing.Image image = System.Drawing.Image.FromStream(inputstream);
            MakeThumbnailBase(image, newFile, maxWidth, maxHeight, Quality, false, WaterMark.None, new WaterMarkContent());
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="inputstream">Image文件流</param>
        /// <param name="newFile">生成的文件名称；注：全路径</param>
        /// <param name="maxWidth">生成图片的宽</param>
        /// <param name="maxHeight">生成图片高</param>
        /// <param name="Quality">生成图片质量</param>
        /// <param name="FixedSize">指定大小生成图片，不足处用透明底色填补</param>
        /// <param name="waterMark">水印</param>
        /// <param name="waterMarkContent">水印详细参数</param>
        public static void MakeThumbnail(Stream inputstream, string newFile, int maxWidth, int maxHeight, int Quality, bool FixedSize, WaterMark waterMark, WaterMarkContent waterMarkContent)
        {
            System.Drawing.Image image = System.Drawing.Image.FromStream(inputstream);
            MakeThumbnailBase(image, newFile, maxWidth, maxHeight, Quality, FixedSize, waterMark, waterMarkContent);
        }

        /// <summary>
        /// 生成缩略图，此方法省略两个参数：｛是否指定大小生成图片=按图片比例缩放，是否需要打上水印=不打水印｝
        /// </summary>
        /// <param name="inputstream">Image文件路径</param>
        /// <param name="newFile">生成的文件名称；注：全路径</param>
        /// <param name="maxWidth">生成图片的宽</param>
        /// <param name="maxHeight">生成图片高</param>
        /// <param name="Quality">生成图片质量</param>
        public static void MakeThumbnail(string strImgPath, string newFile, int maxWidth, int maxHeight, int Quality)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(strImgPath);
            MakeThumbnailBase(image, newFile, maxWidth, maxHeight, Quality, false, WaterMark.None, new WaterMarkContent());
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="inputstream">Image文件路径</param>
        /// <param name="newFile">生成的文件名称；注：全路径</param>
        /// <param name="maxWidth">生成图片的宽</param>
        /// <param name="maxHeight">生成图片高</param>
        /// <param name="Quality">生成图片质量</param>
        /// <param name="FixedSize">指定大小生成图片，不足处用透明底色填补</param>
        /// <param name="waterMark">水印</param>
        /// <param name="waterMarkContent">水印详细参数</param>
        public static void MakeThumbnail(string strImgPath, string newFile, int maxWidth, int maxHeight, int Quality, bool FixedSize, WaterMark waterMark, WaterMarkContent waterMarkContent)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(strImgPath);
            MakeThumbnailBase(image, newFile, maxWidth, maxHeight, Quality, FixedSize, waterMark, waterMarkContent);
        }

        /// <summary>
        /// 生成高清晰缩略图基方法，图片按比例大小缩放，可以生成固定大小的图片，不足处以透明背景填充
        /// </summary>
        /// <param name="image"></param>
        /// <param name="newFile"></param>
        /// <param name="maxWidth"></param>
        /// <param name="maxHeight"></param>
        /// <param name="Quality"></param>
        /// <param name="FixedSize">当此值为true时，生成固定大小图片时，不足处以透明背景填充</param>
        /// <param name="waterMark"></param>
        private static void MakeThumbnailBase(System.Drawing.Image image, string newFile, int maxWidth, int maxHeight, int Quality, bool FixedSize, WaterMark waterMark, WaterMarkContent waterMarkContent)
        {
            int OldWidth = image.Width;//图片实际宽度
            int OldHeight = image.Height;//图片实际高度
            int NewWidth = maxWidth;
            int NewHeight = maxHeight;
            int x = 0;
            int y = 0;

            string mode = string.Empty;
            if (OldWidth <= NewWidth && OldHeight <= NewHeight)
            {
                if (FixedSize)
                {
                    x = (maxWidth - OldWidth) / 2;
                    y = (maxHeight - OldHeight) / 2;
                }
                NewWidth = OldWidth;
                NewHeight = OldHeight;
            }
            else if (OldWidth > NewWidth && OldHeight < NewHeight)
                mode = "W";
            else if (OldWidth < NewWidth && OldHeight > NewHeight)
                mode = "H";
            else if (OldWidth >= NewWidth && OldHeight >= NewHeight)
                if (OldWidth * NewHeight > NewWidth * OldHeight)
                    mode = "W";
                else
                    mode = "H";

            switch (mode)
            {
                case "W"://指定宽，高按比例                    
                    NewHeight = OldHeight * NewWidth / OldWidth;
                    if (FixedSize)
                        y = (maxHeight - NewHeight) / 2;
                    break;
                case "H"://指定高，宽按比例
                    NewWidth = OldWidth * NewHeight / OldHeight;
                    if (FixedSize)
                        x = (maxWidth - NewWidth) / 2;
                    break;
            }

            Bitmap outBmp;
            if (FixedSize)
                outBmp = new Bitmap(maxWidth, maxHeight);
            else
                outBmp = new Bitmap(NewWidth, NewHeight);
            Graphics g = Graphics.FromImage(outBmp);

            // 设置画布描绘质量及背景
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;//指定插值质量
            g.CompositingQuality = CompositingQuality.HighQuality;//指定影像合成
            g.SmoothingMode = SmoothingMode.HighQuality;//指定平滑度
            g.Clear(System.Drawing.Color.Transparent);//清除背景以透明色填充

            //在指定位置并且按指定大小绘制指定的Image的指定部分。
            //当启用高质量插值后会在图片周围产生白线，根据具体情况对下面的参数值进行微调
            g.DrawImage(image, new System.Drawing.Rectangle(x, y, NewWidth + 1, NewHeight), new System.Drawing.Rectangle(4, 4, OldWidth - 4, OldHeight - 4), GraphicsUnit.Pixel);

            #region 添加水印
            //添加文字水印(可设文字透明度)
            if (waterMark == WaterMark.Both || waterMark == WaterMark.Text)
            {
                System.Drawing.Font _Font = new System.Drawing.Font(waterMarkContent.FontFimily, waterMarkContent.FontSize);
                //Color.FromArgb(a,r,g,b) 参数说明：a-透明度0-100,100表示不透明; r-红色; g-绿色; b-蓝色
                string[] ArrARGB = waterMarkContent.FontArgb.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                System.Drawing.Brush _Brush = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(int.Parse(ArrARGB[0]), int.Parse(ArrARGB[1]), int.Parse(ArrARGB[2]), int.Parse(ArrARGB[3])));

                string strWaterMarkText = waterMarkContent.Text;

                //根据字体及字体大小获取字符串所占宽度及高度
                SizeF _SizeF = g.MeasureString(strWaterMarkText, _Font);

                //设置水印位置
                if (FixedSize)
                {
                    x = (maxWidth - NewWidth) / 2;
                    y = (maxHeight + NewHeight) / 2 - Convert.ToInt32(_SizeF.Height);
                }
                else
                {
                    y = NewHeight - Convert.ToInt32(_SizeF.Height);
                }

                g.DrawString(strWaterMarkText, _Font, _Brush, x, y);
            }

            //添加图片水印（可设图片透明度）
            if (waterMark == WaterMark.Both || waterMark == WaterMark.Image)
            {
                System.Drawing.Image WaterMarkImage = System.Drawing.Image.FromFile(waterMarkContent.Img);
                System.Drawing.Imaging.ImageAttributes _ImageAttributes = new System.Drawing.Imaging.ImageAttributes();

                ColorMap colorMap = new ColorMap();
                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                ColorMap[] remapTable = { colorMap };
                _ImageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                //第四行第四个值用来设置透明度，值越大越不透明: 1为不透明、0为全透明
                //正对角线的值分别代表红、绿、蓝、透明度、第五个值也没做太深入研究，想了解ColorMatrix即5x5矩阵可以在网上搜一下，这个矩阵的各个值的设置听说还申请了专利。
                float[][] colorMatrixElements = {  
                new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},  
                new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},  
                new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},  
                new float[] {0.0f, 0.0f, 0.0f, waterMarkContent.ImgAlpha, 0.0f},
                new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}  
                };
                System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements);
                _ImageAttributes.SetColorMatrix(colorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap);

                //设置水印位置
                if (FixedSize)
                {
                    x = (maxWidth + NewWidth - 2 * WaterMarkImage.Width) / 2;
                    y = (maxHeight + NewHeight - 2 * WaterMarkImage.Height) / 2;
                }
                else
                {
                    x = NewWidth - WaterMarkImage.Width;
                    y = NewHeight - WaterMarkImage.Height;
                }

                g.DrawImage(WaterMarkImage, new System.Drawing.Rectangle(x, y, WaterMarkImage.Width, WaterMarkImage.Height), 0, 0, WaterMarkImage.Width, WaterMarkImage.Height, System.Drawing.GraphicsUnit.Pixel, _ImageAttributes);

                WaterMarkImage.Dispose();
                _ImageAttributes.Dispose();
            }
            #endregion

            #region 知识补充
            //g.DrawArc 绘制一段弧线，它表示由一对坐标、宽度和高度指定的椭圆部分。 
            //g.DrawBezier 绘制由4个Point结构定义的贝塞尔样条。
            //g.DrawBeziers 用Point结构数组绘制一系列贝塞尔样条。
            //g.DrawClosedCurve 绘制由Point结构的数组定义的闭合基数样条。
            //g.DrawCurve 绘制经过一组指定的Point结构的基数样条。 
            //g.DrawEllipse 绘制一个由边框（该边框由一对坐标、高度和宽度指定）定义的椭圆。
            //g.DrawIcon 在指定坐标处绘制由指定的 Icon 表示的图像。 
            //g.DrawIconUnstretched 绘制指定的 Icon 表示的图像，而不缩放该图像。 
            //g.DrawImage 在指定位置并且按原始大小绘制指定的 Image。 
            //g.DrawImageUnscaled 在由坐标对指定的位置，使用图像的原始物理大小绘制指定的图像。 
            //g.DrawImageUnscaledAndClipped 在不进行缩放的情况下绘制指定的图像，并在需要时剪辑该图像以适合指定的矩形。
            //g.DrawLine 绘制一条连接由坐标对指定的两个点的线条。 
            //g.DrawLines 绘制一系列连接一组 Point 结构的线段。 
            //g.DrawPath 
            //g.DrawPie 绘制一个扇形，该形状由一个坐标对、宽度、高度以及两条射线所指定的椭圆定义。
            //g.DrawPolygon 绘制由一组 Point 结构定义的多边形。 
            //g.DrawRectangle 绘制由坐标对、宽度和高度指定的矩形。
            //g.DrawRectangles 绘制一系列由 Rectangle 结构指定的矩形。 
            //g.DrawString 在指定位置并且用指定的 Brush 和 Font 对象绘制指定的文本字符串.
            #endregion

            //设置图片压缩质量
            EncoderParameters _EncoderParameters = new EncoderParameters(1);
            EncoderParameter _EncoderParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Quality < 30 ? 100 : Quality);
            _EncoderParameters.Param[0] = _EncoderParameter;

            //设定图片保存格式（固定大小时必须保存为png图片，否则无法保证背景透明）
            ImageCodecInfo _ImageCodecInfo = null;
            if (FixedSize)
                _ImageCodecInfo = GetImageCodecInfo("PNG");
            else
                _ImageCodecInfo = GetImageCodecInfo(image.RawFormat.Guid);

            //保存图片
            if (_ImageCodecInfo == null)
                outBmp.Save(newFile, ImageFormat.Png);
            else
                outBmp.Save(newFile, _ImageCodecInfo, _EncoderParameters);

            g.Dispose();
            image.Dispose();
            outBmp.Dispose();
        }

        public static void MakeWaterImgmark(WaterImage waterImg)
        {
            System.Drawing.Image originalImg = System.Drawing.Image.FromFile(waterImg.OriginalImage);
            Bitmap outBmp = new Bitmap(originalImg);
            Graphics g = Graphics.FromImage(outBmp);

            // 设置画布描绘质量及背景
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;//指定插值质量
            g.CompositingQuality = CompositingQuality.HighQuality;//指定影像合成
            g.SmoothingMode = SmoothingMode.HighQuality;//指定平滑度
           // g.Clear(System.Drawing.Color.Transparent);//清除背景以透明色填充

            System.Drawing.Image WaterMarkImage = System.Drawing.Image.FromFile(waterImg.WaterImg);
            System.Drawing.Imaging.ImageAttributes _ImageAttributes = new System.Drawing.Imaging.ImageAttributes();

            ColorMap colorMap = new ColorMap();
            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };
            _ImageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            //第四行第四个值用来设置透明度，值越大越不透明: 1为不透明、0为全透明
            //正对角线的值分别代表红、绿、蓝、透明度、第五个值也没做太深入研究，想了解ColorMatrix即5x5矩阵可以在网上搜一下，这个矩阵的各个值的设置听说还申请了专利。
            float[][] colorMatrixElements = {  
                new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},  
                new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},  
                new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},  
                new float[] {0.0f, 0.0f, 0.0f, waterImg.ImgAlpha, 0.0f},
                new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}  
                };
            System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements);
            _ImageAttributes.SetColorMatrix(colorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            g.DrawImage(WaterMarkImage, new System.Drawing.Rectangle(waterImg.LocationX, waterImg.LocationY, WaterMarkImage.Width, WaterMarkImage.Height), 0, 0, WaterMarkImage.Width, WaterMarkImage.Height, System.Drawing.GraphicsUnit.Pixel, _ImageAttributes);

            WaterMarkImage.Dispose();
            _ImageAttributes.Dispose();

            outBmp.Save(waterImg.NewFile);

            g.Dispose();
            originalImg.Dispose();
            outBmp.Dispose();
        }

        /// <summary>
        /// 剪裁图片
        /// </summary>
        /// <param name="img">图片对象(原图)</param>
        /// <param name="oldWidth">原图显示定义的宽</param>
        /// <param name="oldHeight">原图显示定义的高</param>
        /// <param name="originalWidth">原图宽</param>
        /// <param name="originalHeight">原图高</param>
        /// <param name="rect">剪裁区域</param>
        /// <param name="savePath">保存路径</param>
        /// <returns>boolen</returns>
        public static string ImageCropping(Image img, float oldWidth, float oldHeight, float originalWidth,
            float originalHeight, Rectangle rect, string savePath,string config,string filename,string filetype)
        {
            if (img != null)
            {
                Image image = img;

                //计算原图与原图缩略显示时的比例
                float widthScale = 0;
                float heightScale = 0;
                widthScale = (originalWidth > 0 && oldWidth > 0) ? originalWidth / oldWidth : 1;
                heightScale = (originalHeight > 0 && oldHeight > 0) ? originalHeight / oldHeight : 1;

                //根据比例更改剪裁区域；以保证前端剪裁预览效果与最终剪裁图片一致；
                if (widthScale > 0 && heightScale > 0)
                {
                    rect.X = (int)(rect.X * widthScale);
                    rect.Y = (int)(rect.Y * heightScale);
                    rect.Width = (int)(rect.Width * widthScale);
                    rect.Height = (int)(rect.Height * heightScale);
                }

                //如果剪裁区域符合规则则开始剪裁
                if (rect.X >= 0 && rect.Y >= 0 && rect.Width >= 0 && rect.Height >= 0)
                {

                    //图片剪裁
                    Bitmap bm = new Bitmap(image);

                    //克隆一张图片对象并剪裁
                    Bitmap coloneBitmap = bm.Clone(rect, bm.PixelFormat);

                    //试图保存一张图片
                    try
                    {
                        coloneBitmap.Save(AppDomain.CurrentDomain.BaseDirectory+savePath+filename+"."+filetype,bm.RawFormat);
                        image.Dispose();
                        bm.Dispose();
                        coloneBitmap.Dispose();
                        return UploadFile.SaveSmallImage(config, savePath, AppDomain.CurrentDomain.BaseDirectory + savePath + filename + "." + filetype, filename, filetype); ;
                    }
                    catch (Exception)
                    {
                        return "";
                    }
                }
            }
            return "";
        }

        /// <summary>
        /// 根据FormatDescription获取ImageCodeInfo
        /// </summary>
        /// <param name="strFormatDescription"></param>
        /// <returns></returns>
        private static ImageCodecInfo GetImageCodecInfo(string strFormatDescription)
        {
            ImageCodecInfo _ImageCodecInfo = null;
            ImageCodecInfo[] ArrImageCodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (var obj in ArrImageCodecInfo)
            {
                if (obj.FormatDescription == strFormatDescription.ToUpper())
                {
                    _ImageCodecInfo = obj;
                    break;
                }
            }
            return _ImageCodecInfo;
        }

        /// <summary>
        /// 根据Guid获取ImageCodeInfo
        /// </summary>
        /// <param name="_Guid"></param>
        /// <returns></returns>
        private static ImageCodecInfo GetImageCodecInfo(Guid _Guid)
        {
            ImageCodecInfo _ImageCodecInfo = null;
            ImageCodecInfo[] ArrImageCodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (var obj in ArrImageCodecInfo)
            {
                if (obj.FormatID == _Guid)
                {
                    _ImageCodecInfo = obj;
                    break;
                }
            }
            return _ImageCodecInfo;
        }

        public enum WaterMark
        {
            None,
            Text,
            Image,
            Both
        }

        public class WaterMarkContent
        {
            public string Text { get; set; }
            public string FontFimily { get; set; }
            public float FontSize { get; set; }
            /// <summary>
            /// 文字颜色及透明度 Color.FromArgb(a,r,g,b) 参数说明：a-透明度0-100,100表示不透明; r-红色; g-绿色; b-蓝色 
            /// </summary>
            public string FontArgb { get; set; }
            /// <summary>
            /// 水印图片物理路径
            /// </summary>
            public string Img { get; set; }
            /// <summary>
            /// 水印图片透明度，值越大越不透明: 1为不透明、0为全透明, 此值类型为float
            /// </summary>
            public float ImgAlpha { get; set; }
        }

       
    }
}
